package com.qa.filter;

import com.alibaba.fastjson.JSONObject;
import com.qa.common.context.BaseContext;
import com.qa.common.utils.StringRedisUtil;
import com.qa.common.utils.TokenUtil;
import com.qa.pojo.entity.User;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 徐
 */
@Slf4j
@Component
public class GetIdFromTokenFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisUtil redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        log.info("token=" + token);

        if (!StringUtils.hasText(token)) {
            // 放行
            filterChain.doFilter(request, response);
            return;
        }

        // 解析token
        String userid;
        try {
            Claims claims = TokenUtil.parseClaim(token).getPayload();
            userid = (String) claims.get("userId");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        // 从redis中获取用户信息
        String redisKey = "login:" + userid;
        log.info("redisKey=" + redisKey);
        String loginUserString = redisCache.getCacheObject(redisKey);
        User loginUser = JSONObject.parseObject(loginUserString, User.class);
        if (Objects.isNull(loginUser)) {
            return;
        }
        BaseContext.setCurrentId(loginUser.getId());
        // 放行
        filterChain.doFilter(request, response);
    }
}
